import os
import django
import sys
from datetime import datetime

sys.path.insert(0, "./")

os.environ.setdefault('DJANGO_SETTINGS_MODULE','fund.settings')

django.setup()

from fundinfo.models import *
from analysis.price_analysis import PriceAnalysis
from trading.models import *

def read_fund_price(code):
    price = PriceAnalysis(code)
    price.setPriceDir("../data/")
    price.readPriceData()
    data = price.price
    return data

def save_fund_info(code, date, cost, count):
    #dt1 = datetime.strptime(date, '%Y-%m-%d')
    #date = datetime.date(dt1)
    tmp = Trading.objects.filter(code=code, date=date)
    if tmp.exists():
        print("--------------exist data------------", code, date)
        return

    trading = Trading()
    trading.code = code
    trading.date = date
    trading.cost = float(cost)
    trading.units = float(count)
    trading.save()
    print("save data:", code, date, cost, count)
    return


def find_trading_date(data, commit_day, price):
    find = False
    for item in reversed(data):
        date_str = item.date.strftime("%Y-%m-%d")
        #print(item.date, date_str)
        if date_str == commit_day:
            find = True
            print('============')
            continue
        if find:
            if item.jjjz == price:
                print("find trading day:", item.date)
                return item.date
    print("not find trading day")
    return None

def read_data(filename):
    fp = open(filename)
    for line in fp:
        items = line.strip().split()
        if len(items) < 9:
            continue
        code = items[0]
        data = read_fund_price(code)
        date1 = items[8]
        print(code, date1, float(items[4]))
        dt1 = find_trading_date(data, date1, float(items[4]))
        if dt1 is None:
            print("not find trading day:", date1)
            continue
        if items[2] == "申购" or items[2] == "定时定额投资":
            save_fund_info(code, dt1, items[5], items[6])
        if items[2] == "赎回":
            save_fund_info(code, dt1, -float(items[5]), -float(items[6]))
        if items[2] == "红利":
            save_fund_info(code, dt1, -float(items[5]), float(items[6]))
        #break
    fp.close()
    return

#read_data("tools/data.txt")
#find_trading_date(data, "2025-09-19", 1.5193)